using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class GameManager : MonoBehaviour
{
    private readonly float RespawnTime = 3f;
    private readonly float InvincibleTime = 5f;
    private int lives = 3;
    private int score = 0;
    [SerializeField]
    private PlayerCon player;
    [SerializeField]
    private ParticleSystem explosion;
    [SerializeField]
    private Canvas canvas;
    private Text liveText;
    private Text scoreText;
    private Transform gameoverObject;
    private Transform scoreObject;
    private Transform livesObject;
    private bool gameIsOver = false;

    private void Awake()
    {
        gameoverObject = canvas.transform.Find("gameover");
        scoreObject = canvas.transform.Find("score");
        livesObject = canvas.transform.Find("Lives");

        scoreText = scoreObject.GetComponent<Text>();
        liveText = livesObject.GetComponent<Text>();

        if (gameoverObject != null)
        {
            gameoverObject.gameObject.SetActive(false);
        }
    }
    private void Start()
    {
        scoreText.text = score.ToString();
        liveText.text = "x " + lives.ToString();
    }
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Y) && gameIsOver)
        {
            gameoverObject.gameObject.SetActive(false);
            lives = 3;
            score = 0;
            liveText.text = "x " + lives.ToString();
            scoreText.text = score.ToString();
            Invoke(nameof(RespawnPlayer), 1f);
            gameIsOver = false;
        }
    }
    public void PlayerDied()
    {
        explosion.transform.position = player.transform.position;
        explosion.Play();
        lives--;
        liveText.text = "x " + lives.ToString();
        if (lives <= 0)
        {
            GameOver();
        }
        else
        {
            Invoke(nameof(RespawnPlayer), RespawnTime);
        }
    }

    public void AsteroidDestroy(Asteriod asteriod)
    {
        explosion.transform.position = asteriod.transform.position;
        explosion.Play();
        if (asteriod._size <= 1.0f)
        {
            score += 100;
        }
        else if (asteriod._size <= 1.5f)
        {
            score += 50;
        }
        else
        {
            score += 25;
        }
        scoreText.text = score.ToString();
    }


    private void GameOver()
    {
        gameoverObject.gameObject.SetActive(true);
        gameIsOver = true;
    }

    private void RespawnPlayer()
    {
        player.transform.position = Vector3.zero;
        player.transform.eulerAngles = Vector3.zero;
        player.gameObject.layer = LayerMask.NameToLayer("Invincible");
        player.gameObject.SetActive(true);
        Invoke(nameof(TurnLayer), InvincibleTime);
    }

    private void TurnLayer()
    {
        player.gameObject.layer = LayerMask.NameToLayer("Player");
    }
}
